<template>
  <div>
    <el-card shadow="never" class="mb20">
      <div slot="header" style="overflow:hidden;line-height:32px">
        <span>资产信息</span>
        <el-button class="fr" size="small" type="primary" @click="handlePrint">标签打印</el-button>
        <el-button
          class="fr mr20"
          size="small"
          type="primary"
          :loading="loading"
          @click="handleEdit"
        >{{ !isEdit ? '保存' : '编辑' }}</el-button>
      </div>
      <el-form :model="form" ref="form" label-width="100px" :rules="!isEdit ? rules : {}">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="assetsName" label="资产名称:">
              <span v-if="isEdit">{{ form.assetsName }}</span>
              <el-autocomplete
                v-else
                :style="fixWidth"
                v-model="form.assetsName"
                :fetch-suggestions="supplierQueryAsync"
                placeholder="请输入资产名称"
                @select="handleAssetsSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="categoryId" label="资产类别:">
              <span v-if="isEdit">{{ form.categoryName }}</span>
              <type-select
                v-else
                :selectValue="form.categoryId"
                :selectStyle="fixWidth"
                ref="typeSelect"
                @select="value => handleSelect('categoryId', value)"
                v-model="form.categoryId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:">
              <el-tag
                v-if="isEdit"
                :type="stateType(form.assetsState)"
              >{{stateWord(form.assetsState)}}</el-tag>
              <!-- <span v-if="isEdit">{{ form.assetsState }}</span> -->
              <el-select
                clearable
                v-else
                :style="fixWidth"
                v-model="form.assetsState"
                placeholder="请选择状态"
              >
                <el-option value="0" label="正常" />
                <el-option value="1" label="遗失" />
                <el-option value="2" label="标签破损" />
                <el-option value="3" label="维修" />
                <el-option value="4" label="报废" />
                <el-option value="5" label="违规异动" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌:">
              <span v-if="isEdit">{{ form.brand }}</span>
              <el-input
                v-else
                :style="fixWidth"
                type="text"
                v-model="form.brand"
                placeholder="请输入品牌名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号:">
              <span v-if="isEdit">{{ form.specification }}</span>
              <el-input
                v-else
                :style="fixWidth"
                placeholder="请输入规格型号"
                v-model="form.specification"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位:">
              <span v-if="isEdit">{{ form.unit }}</span>
              <el-input v-else :style="fixWidth" placeholder="请输入计量单位" v-model="form.unit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商:">
              <span v-if="isEdit">{{ form.supplier }}</span>
              <el-autocomplete
                v-else
                :style="fixWidth"
                v-model="form.supplier"
                :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, true, 'supplier')"
                placeholder="请输入供应商名称"
                @select="value => supplierSelect(value, 'supplier', 'supplierCode')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="factory" label="生产厂家:">
              <span v-if="isEdit">{{ form.factory }}</span>
              <el-input v-else :style="fixWidth" placeholder="请输入生产厂家" v-model="form.factory" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买日期:">
              <span v-if="isEdit">{{ form.buyDate }}</span>
              <el-date-picker
                v-else
                :style="fixWidth"
                type="date"
                placeholder="请选择购买日期"
                value-format="yyyy-MM-dd"
                v-model="form.buyDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="expireDate" label="到期日期:">
              <span v-if="isEdit">{{ form.expireDate }}</span>
              <el-date-picker
                v-else
                :disabled="true"
                :style="fixWidth"
                value-format="yyyy-MM-dd"
                placeholder="请选择到期日期"
                v-model="form.expireDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产原值:">
              <span v-if="isEdit">{{ form.price }}</span>
              <el-input v-else v-model="form.price" :style="fixWidth" placeholder="请输入资产原值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产净值:">
              <span v-if="isEdit">{{ form.nowPrice }}</span>
              <el-input v-else v-model="form.nowPrice" :style="fixWidth" placeholder="请输入资产净值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折旧年限(月):">
              <span v-if="isEdit">{{ form.serviceLife }}</span>
              <el-input
                v-else
                :readOnly="true"
                :style="fixWidth"
                v-model.number="form.serviceLife"
                placeholder="请输入使用期限"
                allowClear
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放地点:">
              <span v-if="isEdit">{{ form.storageLocation }}</span>
              <el-input
                v-else
                :style="fixWidth"
                placeholder="请输入存放地点"
                v-model="form.storageLocation"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="useDeptId" label="使用部门:">
              <span v-if="isEdit">{{ form.useDept }}</span>
              <dept-select
                v-else
                :selectValue="form.useDeptId"
                :selectStyle="fixWidth"
                ref="userSelect"
                @select="value => handleSelect('useDeptId', value)"
                v-model="form.useDeptId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用人:">
              <span v-if="isEdit">{{ form.useUser }}</span>
              <dept-user
                v-else
                :deptId="userDeptId"
                :selectStyle="fixWidth"
                :selectValue="form.useUserId"
                ref="userSelect"
                @select="value => handleSelect('useUserId', value)"
                v-model="form.useUserId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门:">
              <span v-if="isEdit">{{ form.belognDept }}</span>
              <dept-select
                v-else
                :selectValue="form.belongDeptId"
                :selectStyle="fixWidth"
                ref="userSelect"
                @select="value => handleSelect('belongDeptId', value)"
                v-model="form.belongDeptId"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="管理员:">
              <span v-if="isEdit">{{ form.manageUser }}</span>
              <dept-user
                v-else
                :deptIdManage="userDeptIdM"
                :selectStyle="fixWidth"
                :selectValue="form.manageUserId"
                ref="areaSelect"
                @select="value => handleSelect('manageUserId', value)"
                v-model="form.manageUserId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在区域:" style="height: 36px">
              <span v-if="isEdit">{{ form.areaName }}</span>
              <area-select
                v-else
                :selectStyle="fixWidth"
                :selectValue="form.areaId"
                ref="areaSelect"
                @select="value => handleSelect('areaId', value)"
                v-model="form.areaId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="汇总物件:">
              <span v-if="isEdit">{{ form.summaryFlag ? '是' : '否' }}</span>
              <el-radio-group
                size="medium"
                @change="handleSummaryChange"
                v-else
                v-model="form.summaryFlag"
              >
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.summaryFlag">
            <el-form-item label="汇总数量:">
              <span v-if="isEdit">{{ form.summaryNumber }}</span>
              <el-input
                :style="fixWidth"
                v-else
                v-model.number="form.summaryNumber"
                placeholder="请输入汇总数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后打印人:">{{ form.printUser }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后打印时间:">{{ form.printTime ? formatTime(form.printTime) : null }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div slot="header" style="overflow:hidden;line-height:32px">
        <span>资产图片</span>
        <el-upload
          class="upload-demo fr"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="handleChange"
          :http-request="httpRequest"
        >
          <el-button size="small" type="primary" :disabled="isEdit">点击上传</el-button>
        </el-upload>
      </div>
      <template v-if="listData.length">
        <el-row>
          <el-col
            class="mr20"
            style="overflow:hidden"
            :span="4"
            v-for="(item,index) in fileList"
            :key="index"
          >
            <el-image
              @click="handlePreview(item)"
              :style="{ width: '250px',height: '250px' }"
              :src="item.url"
              fit="cover"
            />
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <empty-comp ref="emptyComp" />
      </template>
    </el-card>
    <preview-modal ref="previewModal" />
    <print-modal ref="printModal" />
  </div>
</template>

<script>
import PrintModal from '../info/PrintModal'
import DeptUser from '../components/DeptUser'
import DeptSelect from '../components/DeptSelect'
import AreaSelect from '../components/AreaSelect'
import TypeSelect from '../components/TypeSelect'
import PreviewModal from '@/components/PreviewModal'
import { infoUpdate, categoryTree, fuzzyQuery, supplierFuzzyQuery, createSupplier } from '@/api/assetsNew'
import { openNotification } from '@/utils/util'
import { saveOnlyUploads } from '@/api/assets'
import moment from 'moment'

export default {
  components: {
    DeptUser,
    AreaSelect,
    DeptSelect,
    TypeSelect,
    PreviewModal,
    PrintModal
  },
  computed: {
    computeDate() {
      const { serviceLife, buyDate } = this.form
      if (serviceLife && buyDate) {
        let buyYear = buyDate.split('-')[0]
        let buyMonth = buyDate.split('-')[1]
        let buyDay = buyDate.split('-')[2]
        if (serviceLife > 12) {
          let year = 0
          let month = 0
          if (serviceLife % 12 === 0) {
            year = serviceLife / 12
          } else {
            year = Math.floor(serviceLife / 12)
            month = serviceLife % 12
          }
          buyYear = Number(buyYear) + Number(year)
          buyMonth = Number(buyMonth) + Number(month)
        } else {
          const month = serviceLife % 12
          buyMonth = Number(buyMonth) + Number(month)
        }
        const expireDate = moment(buyYear + '-' + buyMonth + '-' + buyDay).format('YYYY-MM-DD')
        this.$set(this.form, 'expireDate', expireDate)
      }
    },
    computeNowPrice() {
      const { price, serviceLife, buyDate } = this.form
      // 计算月份差值
      const nowDate = moment(new Date()).format('YYYY-MM')
      const nowYear = nowDate.split('-')[0]
      const nowMonth = nowDate.split('-')[1]
      const oldDate = moment(buyDate).format('YYYY-MM')
      const oldYear = oldDate.split('-')[0]
      const oldMonth = oldDate.split('-')[1]
      let monthAll = 0
      let monthYear = 0
      let monthM = 0
      if (nowYear - oldYear > 0) {
        monthYear = (nowYear - oldYear) * 12
      }
      if (nowMonth - oldMonth > 0) {
        monthM = nowMonth - oldMonth
      }
      monthAll = monthYear + monthM

      if (price && serviceLife && buyDate) {
        let nowPrice = price * (1 - monthAll / serviceLife)
        if (nowPrice > 0) {
          this.$set(this.form, 'nowPrice', nowPrice)
        } else {
          this.$message.info('资产净值已小于0，资产状态已选择为报废，请知悉')
          this.$set(this.form, 'nowPrice', 0)
          this.$set(this.form, 'assetsState', 4)
        }
      }
    }
  },
  watch: {
    computeDate(n, o) {
      console.log('date n', n, o)
    },
    computeNowPrice(n, o) {
      console.log('n', n, o)
    }
  },
  data() {
    return {
      mdl: {},
      fixWidth: {
        width: '300px'
      },
      loading: false,
      isEdit: true,
      // useDeptId: null,
      // useUserId: null,
      // areaId: null,
      form: {
        assetsId: null,
        assetsName: null,
        categoryId: null,
        state: null,
        brand: null,
        belongDeptId: null,
        useDeptId: null,
        useUserId: null,
        manageUserId: null,
        areaId: null,
        supplierName: null,
        supplierCode: null,
        brand: null,
        factory: null,
        buyDate: null,
        serviceLife: null,
        expireDate: null,
        storageLocation: null,
        specification: null,
        unit: null,
        summaryFlag: null, // 是否汇总
        lableType: null,
        summaryNumber: 1 // 汇总数量
      },
      rules: {
        assetsName: [{ required: true, trigger: 'blur', message: '请输入固定资产名称' }],
        categoryId: [{ required: true, trigger: 'blur', message: '请选择固定资产类型' }],
        useDeptId: [{ required: true, trigger: 'change', message: '请选择使用部门' }],
        useUserId: [{ required: true, trigger: 'change', message: '请选择使用人' }],
        manageUserId: [{ required: true, trigger: 'change', message: '请选择管理员' }],
        areaId: [{ required: true, trigger: 'change', message: '请选择所在区域' }],
        antiFlag: [{ required: true, trigger: 'blur', message: '请选择标签材质' }]
      },
      userDeptIdM: '',
      userDeptId: '',
      fileList: [],
      listData: [{ url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' }, { url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' }]
    }
  },
  methods: {
    stateWord(num) {
      let str = ''
      switch (num) {
        case '0':
          str = '正常'
          break
        case '1':
          str = '遗失'
          break
        case '2':
          str = '标签破损'
          break
        case '3':
          str = '维修'
          break
        case '4':
          str = '报废'
          break
        case '5':
          str = '违规异动'
          break
        default:
          break
      }
      return str
    },
    stateType(num) {
      let str = ''
      switch (num) {
        case '0':
          str = 'success'
          break
        case '1':
          str = 'danger'
          break
        case '2':
          str = 'orange'
          break
        case '3':
          str = ''
          break
        case '4':
          str = 'danger'
          break
        case '5':
          str = 'info'
          break
        default:
          break
      }
      return str
    },
    handleSummaryChange(e) {
      // console.log('e', e)
      if (!e) {
        this.$set(this.form, 'summaryNumber', null)
      }
    },
    // 父组件绑定数据
    edit(obj) {
      console.log('obj', obj)

      this.form = Object.assign({}, obj)
      this.userDeptIdM = obj.belongDeptId
      this.userDeptId = obj.useDeptId
      this.fileList = [...obj.pictureUrl]
    },
    // 打印事件处理
    handlePrint() {
      this.$refs.printModal.edit(this.form)
    },
    handlePreview(item) {
      this.$refs.previewModal.show([item.url])
    },
    handleSelect(key, value) {
      this.$set(this.form, key, value.id)
      if (key === 'useDeptId') {
        this.userDeptId = value
        this.$set(this.form, 'useUserId', null)
      }
      if (key === 'belongDeptId') {
        this.userDeptIdM = value
        this.$set(this.form, 'manageUserId', null)
      }
    },
    nameFilter(queryString) {
      return state => {
        // console.log('state', state)
        return state.assetsName.indexOf(queryString) >= 0
      }
    },
    supplierFilter(queryString) {
      return state => {
        // console.log('state', state)
        return state.supplier.indexOf(queryString) >= 0
      }
    },
    async supplierQueryAsync(queryString, cb, bool, mode) {
      console.log('bool', bool)
      if (mode === 'supplier') {
        this.$set(this.form, 'supplierCode', null)
      } else {
        this.$set(this.form, 'factoryCode', null)
      }
      queryString = queryString === undefined ? null : queryString
      let results = []
      if (queryString) {
        console.log('queryString', queryString)
        let res = ''
        if (bool) {
          res = await supplierFuzzyQuery({ supplierName: queryString })
        } else {
          res = await fuzzyQuery({ assetsName: queryString })
        }
        var supplier = res.data
        if (queryString) {
          if (bool) {
            // 过滤供应商
            results = supplier.filter(this.supplierFilter(queryString))
          } else {
            results = supplier.filter(this.nameFilter(queryString))
          }
        } else {
          results = supplier
        }
        if (bool) {
          results.map(v => {
            v.value = v.supplier
          })
        } else {
          results.map(v => {
            v.value = v.assetsName
          })
        }
        // console.log('results', results)
        if (results.length === 0) {
          if (bool) {
            // 供应商
            results.push({
              value: `新增[${queryString}]`,
              supplier: queryString,
              supplierId: '-1'
            })
          }
        }

        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 1000 * Math.random())
      } else {
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 300 * Math.random())
      }
    },
    async supplierSelect(value, key, code) {
      console.log('supplierSelect', value, key)
      if (value.supplierId === '-1') {
        const res = await createSupplier({ name: value.supplier })
        console.log('res', res)
        this.$set(this.form, code, res.data)
      } else {
        this.$set(this.form, code, value.supplierId)
      }
      this.$set(this.form, key, value.supplier)
      console.log('form', this.form)
    },
    handleAssetsSelect(val) {
      console.log('val', val)
      this.form = { ...this.form, ...val }
      // this.$set(this.form, 'assetsName', val.value)
    },
    async handleEdit() {
      // this.isEdit = !this.isEdit
      this.loading = true
      if (!this.isEdit) {
        this.$refs.form.validate(async valid => {
          if (valid) {
            let photoList = null
            if (this.fileList.length > 0) {
              let arr = []
              this.fileList.map(v => {
                arr.push(v.uploadId)
              })
              photoList = arr.join(',')
            }
            let param = { ...this.form, photoList }
            const res = await infoUpdate(param)
            if (res.state === '000000') {
              this.$emit('refresh')
              openNotification('success', '保存操作成功')
              this.isEdit = !this.isEdit
            }
            console.log('res', res)
          }
        })
      } else {
        this.isEdit = !this.isEdit
      }
      this.loading = false
    },
    handleChange(file, fileList) {
      console.log('change', file, fileList)
    },
    async httpRequest(file, fileList) {
      console.log('httpRequest', file, fileList)
      const formData = new FormData()
      formData.append('file', file.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        console.log('res', res)
        if (res.data !== null) {
          const { data } = res
          this.fileList.push(data)
          this.fileList[this.fileList.length - 1].uploadId = data.uploadId
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].status = 'done'
        }
      })
    }
  }
}
</script>

<style scoped>
.upload-demo >>> .el-upload-list {
  display: none;
}
.factory-autocomplete >>> .is-disabled .el-input__inner,
.el-date-editor.is-disabled >>> .el-input__inner {
  background-color: #ffffff !important;
  color: #333333 !important;
  cursor: auto;
}
</style>